<?php

class ApplicationConfig extends Model
{
	function ApplicationConfig()
	{
		parent::Model();
		// génération des constantes PHP au chargement du modèle
		foreach ($this->all() as $config) {
			define($config->key, $config->value);
		}
	}
	
	function all($filter = null)
	{
		$this->db->select('id, key, label, value, value_type, default_value, updated_at, hidden, namespace')
		         ->from('application_config')
		         ->order_by('namespace');
		if ($filter) {
			$this->db->where($filter);
		}
		$query = $this->db->get();
		return $query->result();
	}
	
	function get_by_id($id)
	{
		$this->db->select('id, key, label, value, value_type, default_value, updated_at, hidden, namespace')
		         ->from('application_config')
		         ->where('id', $id);
		$query = $this->db->get();
		return $query->row();
	}
	
	function update($object, $value)
	{
		switch ($object->value_type) {
			case 'T_INT':
				$value = intval($value);
				break;
			case 'T_BOOL':
				$value = $value ? 1 : 0;
				break;
		}
		$object->value = $value;
		$object->updated_at = date_db_format();
		switch ($object->key) {
			case 'POSTS_PER_PAGE':
				return $object->value > 0;
			case 'CONTACT_EMAIL':
				return check_email($object->value);
		}
		return true;
	}
	
	function save($object)
	{
		if ($object->id == null) {
			return $this->db->insert('application_config', $object);
		}
		else {
			$this->db->where('id', $object->id);
			return $this->db->update('application_config', $object);
		}
	}
	
	function titlelize_namespace($namespace)
	{
		switch ($namespace) {
			case 'cms':
				return 'Gestion des contenus';
			case 'server':
				return 'Serveur';
			case 'filesystem':
				return 'Système de fichiers';
		}
		return $namespace;
	}
}


